<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <eHeader :permission="permission" class="header-bottom" />
      <crudOperation :permission="permission" />
      <!--无数据-->
      <el-empty
        v-show="!crud.data || crud.data.length == 0"
        description="暂无数据"
      ></el-empty>
      <!--渲染列表-->
      <el-row
        :gutter="20"
        v-show="crud.data && crud.data.length > 0"
        v-loading="crud.loading"
      >
        <el-col :span="6" v-for="(item, index) in crud.data" :key="item.id">
          <div class="grid-content bg-purple">
            <el-card class="box-card">
              <div class="top">
                <img src="@/assets/images/factory.png" class="img" />
                <div class="content">
                  <div class="titleName">{{ item.modelName }}</div>
                  <div class="subTitle">编码: {{ item.modelCode }}</div>
                  <div class="descWrapper">
                    <div class="descTitle">描述:</div>
                    <div class="descContent">
                      {{ item.remark ? item.remark : " --" }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="bottom">
                <router-link :to="'/factory/model/details/' + item.id">
                  <el-button class="button" size="mini"> 查看 </el-button>
                </router-link>
                <div class="time">创建时间: {{ item.createTime }}</div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
      <!--分页组件-->
      <pagination />
      <!--表单渲染-->
      <eForm inputName="工厂"/>
    </div>
  </div>
</template>

<script>
import crudFactoryModel from "@/api/factory/factoryModel";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import eHeader from "./module/header";
import eForm from "./module/form";

const defaultForm = {
  id: null,
  modelCode: null,
  modelName: null,
  modelType: null,
  remark: null,
  pid: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
};

let that = {};

export default {
  name: "FactoryModel",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    eHeader,
    eForm,
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "工厂建模",
      url: "api/factoryModel",
      idField: "id",
      sort: "id,desc",
      // 主页操作栏显示哪些按钮
      optShow: {
        add: true,
        edit: false,
        del: false,
        download: false,
        reset: true,
        import: true
      },
      importConfig:{
        //模板地址
        templateUrl: '/template/工厂模型导入模板.xlsx',
        //解析Excel成功回调
        onSuccess:  data => {
          return that.analysis(data);
        }
      },
      crudMethod: { ...crudFactoryModel },
    });
  },
  data() {
    return {
      myHeader : ['工厂编码','工厂名称','车间编码','车间名称','产线编码','产线名称','工段编码','工段名称','工站编码','工站名称','设备编码','设备名称'],
      trreData : [],
      permission: {
        add: ["admin", "factoryModel:add"],
        edit: ["admin", "factoryModel:edit"],
        del: ["admin", "factoryModel:del"],
      },
      rules: {},
    };
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.params.modelType = '0';
      return true;
    },
    //解析数据
    analysis(data){
      //校验头部数据
      if(!this.verifyHeader(data.header)){
        return false;
      }
      //保存上一次解析的编码
      let firstFactory,firstWorkshop,firstLine,firstSection,firstStation;
      //错误信息
      let errorMsg = '';
      //解析数据
      data.results.forEach(item => {
        //工厂
        const factoryCd = item[this.myHeader[0]];
        const factoryNm = item[this.myHeader[1]];
        if(factoryCd){
          firstFactory = factoryCd;
          //判断是否已存在
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          if(!factoryNode){
            //不存在则添加
            this.trreData.push(this.createNode(factoryCd,factoryNm,'0'));
          }
        }

        //车间
        const workshopCd = item[this.myHeader[2]];
        const workshopNm = item[this.myHeader[3]];
        if(workshopCd){
          firstWorkshop = workshopCd;
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          let workshopNode = this.getTreeNodeByCd(factoryNode.children,firstWorkshop);
          if(!workshopNode){
            factoryNode.children.push(this.createNode(workshopCd,workshopNm,'1'));
          }
        }

        //产线
        const lineCd = item[this.myHeader[4]];
        const lineNm = item[this.myHeader[5]];
        if(lineCd){
          firstLine = lineCd;
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          let workshopNode = this.getTreeNodeByCd(factoryNode.children,firstWorkshop);
          let lienNode = this.getTreeNodeByCd(workshopNode.children,firstLine);
          if(!lienNode){
            workshopNode.children.push(this.createNode(lineCd,lineNm,'2'));
          }
        }
        //工段
        const sectionCd = item[this.myHeader[6]];
        const sectionNm = item[this.myHeader[7]];
        if(sectionCd){
          firstSection = sectionCd;
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          let workshopNode = this.getTreeNodeByCd(factoryNode.children,firstWorkshop);
          let lienNode = this.getTreeNodeByCd(workshopNode.children,firstLine);
          let sectionNode = this.getTreeNodeByCd(lienNode.children,firstSection);
          if(!sectionNode){
            lienNode.children.push(this.createNode(sectionCd,sectionNm,'3'));
          }
        }

        //工位
        const stationCd = item[this.myHeader[8]];
        const stationNm = item[this.myHeader[9]];
        if(stationCd){
          firstStation = stationCd;
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          let workshopNode = this.getTreeNodeByCd(factoryNode.children,firstWorkshop);
          let lienNode = this.getTreeNodeByCd(workshopNode.children,firstLine);
          let sectionNode = this.getTreeNodeByCd(lienNode.children,firstSection);
          let stationNode = this.getTreeNodeByCd(sectionNode.children,firstStation);
          if(!stationNode){
            sectionNode.children.push(this.createNode(stationCd,stationNm,'4'));
          }
        }

        //设备
        const deviceCd = item[this.myHeader[10]];
        const deviceNm = item[this.myHeader[11]];
        if(deviceCd){
          let factoryNode = this.getTreeNodeByCd(this.trreData,firstFactory);
          let workshopNode = this.getTreeNodeByCd(factoryNode.children,firstWorkshop);
          let lienNode = this.getTreeNodeByCd(workshopNode.children,firstLine);
          let sectionNode = this.getTreeNodeByCd(lienNode.children,firstSection);
          let stationNode = this.getTreeNodeByCd(sectionNode.children,firstStation);
          let deviceNode = this.getTreeNodeByCd(stationNode.children,deviceCd);
          if(!deviceNode){
            stationNode.children.push(this.createNode(deviceCd,deviceNm,'5'));
          } else {
            errorMsg = '解析Excel失败！设备编号不能重复！【'+deviceCd+'】';
            return false;
          }
        } else {
          errorMsg = '解析Excel失败！设备编号不能为空！';
          return false;
        }
      })

      //判断是否有错误
      if(errorMsg != ''){
        this.$notify.error({
          title: '错误',
          message: errorMsg
        });
        return false;
      }

      //上传数据导入
      this.crud.loading = true;
      crudFactoryModel.importTree(this.trreData).then(res =>{
        this.crud.loading = false;
        //刷新
        this.crud.toQuery();
      }).catch((e) => {
        debugger
        this.crud.loading = false;
        this.$notify.error({
          title: '错误',
          message: '导入失败系统发生错误！'
        });
      });

      return true;
    },
    //校验头部
    verifyHeader(header){
      if(header.length != this.myHeader.length){
        this.$notify.error({
          title: '错误',
          message: '解析Excel失败！Excel头部名称不正确！'
        });
        return false;
      }
      let isOk = false;
      this.myHeader.forEach((item,index) =>{
        if(!header[index] || item != header[index]){
          isOk = true;
          return ;
        }
      })
      if(isOk){
        this.$notify.error({
          title: '错误',
          message: '解析Excel失败！Excel头部名称不正确！'
        });
        return false;
      }
      return true;
    },
    //根据编码获取节点
    getTreeNodeByCd(tree,code){
      let noed;
      tree.forEach(item =>{
        if(item.code == code){
          noed = item;
          return ;
        }
      })
      return noed;
    },
    //创建节点
    createNode(code,label,type,children){
      const node = {code : code,label : label,type : type};
      if(children){
        node.children = children;
      } else {
        node.children = [];
      }
      return node;
    }

  },
  mounted() {
    that = this;
    window.onscroll=function(){
      if(document.documentElement.scrollTop>100) {
        that.isActive=true;
      }else{
        that.isActive=false;
      }
    }
  }
};
</script>

<style scoped>
.header-bottom {
  padding-bottom: 10px;
}
.el-card {
  margin-bottom: 15px;
}
.top {
  width: 100%;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  justify-content: flex-start;
  align-items: flex-start;
  font-family: PingFangSC-Regular;
}
.img {
  width: 64px;
  margin-right: 15px;
}
.content {
  overflow: hidden;
  flex: 1 1;
}
.titleName {
  font-size: 14px;
  color: #333;
  line-height: 22px;
  font-weight: 700;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.subTitle {
  font-size: 12px;
  color: #555;
  line-height: 20px;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.descWrapper {
  font-size: 12px;
  color: #555;
  line-height: 20px;
  margin-bottom: 8px;
  display: flex;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.descContent {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  justify-content: flex-start;
}
.bottom .time {
  font-size: 13px;
  color: #999;
}
.bottom .button {
  float: right;
  margin-right: 20px;
}
</style>
